package com.huiquan.medicine.service;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.RespHeaderUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.medicine.dao.MedicineDao;
import com.huiquan.medicine.entity.DiMedicineGroup;
import com.huiquan.medicine.entity.MedicineGroup;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.*;

/**
 * 药品 service
 * 
 * @author leo
 * @time 2017年4月5日 下午5:27:14
 */
@Service
public class MedicineService extends BaseService {
	@Autowired
	private MedicineDao dao;

	/**
	 * 查看药品分组列表
	 *
	 * @param startStr
	 * @param keyword
	 * @return
	 */
	public Map<String, Object> medicineGroupList(String startStr,
			String keyword) {
		int start = startStr == null ? 1 : Integer.parseInt(startStr);
		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", "%" + keyword + "%");
		}
		int totalSize = dao.selectMedicineGroupCount(param);

		Map<String, Integer> pageNo = GetListUtil
				.getPageNoMap(totalSize, start);

		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<MedicineGroup> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = dao.selectMedicineGroupList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "名称");
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start,
				startIndex, endPage, list, null);
		map.put("showSearch", showSearch);
		return map;
	}

	/**
	 * 查看疾病药品分组列表
	 *
	 * @param startStr
	 * @param keyword
	 * @return
	 */
	public Map<String, Object> diMedicineGroupList(String startStr,
			String keyword, String countPerPageStr) {
		int start = startStr == null ? 1 : Integer.parseInt(startStr);
		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", "%" + keyword + "%");
		}
		int totalSize = dao.selectDiMedicineGroupCount(param);

		Map<String, Integer> pageNo;
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "",
					countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<DiMedicineGroup> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = dao.selectDiMedicineGroupList(param);
		}
		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "名称");
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start,
				startIndex, endPage, list, null);
		List<MedicineGroup> groupList = dao.selectMedicineGroupListToExport();
		map.put("groupList", groupList);
		map.put("showSearch", showSearch);
		return map;
	}

	/**
	 * 导入药品分组
	 * 
	 * @param user
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public ReturnData importMedicineGroup(User user, MultipartFile file)
			throws IOException {
		dao.deleteMedicineGroup();
		InputStream excelIn = file.getInputStream();
		InputStreamReader read = new InputStreamReader(excelIn, "UTF-8"); // 考虑到文本编码
		Workbook workbook = new XSSFWorkbook(excelIn);
		Sheet sheet = workbook.getSheetAt(0);
		Map<String, String> params = null;
		// 行数
		int j = 0;
		// 处理每一行
		for (Row row : sheet) {
			int i = 0;
			// 取出每一行记录
			params = new HashMap<>();
			for (Cell cell : row) {
				// 第一行跳过
				cell.setCellType(Cell.CELL_TYPE_STRING);
				String word = cell.getStringCellValue().trim();
				if (i == 0) {
					params.put("groupName", word);
				} else if (i == 1) {
					params.put("id", word);
				} else if (i == 2) {
					params.put("rank", word);
				}
				i++;
			}
			insertMedicineGroup(params, user);
			j++;
		}
		read.close();
		return ReturnUtil.success();
	}

	/**
	 * 导入疾病药品分组
	 * 
	 * @param user
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public ReturnData importDiMedicineGroup(User user, MultipartFile file)
			throws IOException {
		LOGGER.info("import begin!");
		InputStream excelIn = file.getInputStream();
		InputStreamReader read = new InputStreamReader(excelIn, "UTF-8"); // 考虑到文本编码
		Workbook workbook = new XSSFWorkbook(excelIn);
		Sheet sheet = workbook.getSheetAt(0);
		List<DiMedicineGroup> insertList = new ArrayList<>();
		// 处理每一行
		for (Row row : sheet) {
			if (dao.selectIcdDiseaseCountByName(row.getCell(1)
					.getStringCellValue()) > 0) {
				int id = 0;
				String di = "";
				int rank = 0;
				int age = 0;
				int sex = 0;
				for (Cell cell : row) {
					row.getCell(0).setCellType(Cell.CELL_TYPE_NUMERIC);
					row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
					row.getCell(2).setCellType(Cell.CELL_TYPE_NUMERIC);
					row.getCell(3).setCellType(Cell.CELL_TYPE_NUMERIC);
					row.getCell(4).setCellType(Cell.CELL_TYPE_NUMERIC);
					id = (int) row.getCell(0).getNumericCellValue();
					di = row.getCell(1).getStringCellValue();
					rank = (int) row.getCell(2).getNumericCellValue();
					age = (int) row.getCell(3).getNumericCellValue();
					sex = (int) row.getCell(4).getNumericCellValue();
				}
				DiMedicineGroup value = new DiMedicineGroup();
				value.setId(id);
				value.setDi(di);
				value.setRank(rank);
				value.setAge(age);
				value.setSex(sex);
				value.setModifierId(user.getUserId());
				value.setModifierName(user.getRealName());
				insertList.add(value);
			} else {
				// 否则终止导入并提醒
				read.close();
				Map<String, Object> map = new HashMap<>();
				ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				returnCode.setDesc("导入失败，"
						+ row.getCell(1).getStringCellValue() + "  在疾病维表中不存在");
				return new ReturnData(returnCode, map);
			}
		}
		dao.deleteDiMedicineGroup();
		dao.batchInsertDiMedicineGroup(insertList);
		read.close();
		return ReturnUtil.success();
	}

	/**
	 * 更新一条药品分组
	 * 
	 * @param params
	 * @param user
	 */
	public ReturnData updateMedicineGroup(Map<String, String> params, User user) {
		int seq = Integer.valueOf(params.get("seq"));
		MedicineGroup entity = dao.selectMedicineGroupBySeq(seq);
		if (StringUtils.isNotEmpty(params.get("groupName"))) {
			entity.setGroupName(params.get("groupName"));
		}
		if (StringUtils.isNotEmpty(params.get("id"))) {
			entity.setId(Integer.valueOf(params.get("id")));
		}
		if (StringUtils.isNotEmpty(params.get("rank"))) {
			entity.setRank(Integer.valueOf(params.get("rank")));
		}
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.updateMedicineGroup(entity);
		return ReturnUtil.success();
	}

	/**
	 * 更新一条疾病药品分组
	 * 
	 * @param params
	 * @param user
	 */
	public ReturnData updateDiMedicineGroup(Map<String, String> params,
			User user) {
		int seq = Integer.valueOf(params.get("seq"));
		DiMedicineGroup entity = dao.selectDiMedicineGroupBySeq(seq);
		if (StringUtils.isNotEmpty(params.get("id"))) {
			entity.setId(Integer.valueOf(params.get("id")));
		}
		if (StringUtils.isNotEmpty(params.get("di"))) {
			if (dao.selectIcdDiseaseCountByName(params.get("di")) < 1) {
				Map<String, Object> map = new HashMap<>();
				ReturnCode returnCode = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				returnCode.setDesc("更新失败，" + params.get("di") + "  在疾病维表中不存在");
				return new ReturnData(returnCode, map);
			}

			entity.setDi(params.get("di"));
		}
		if (StringUtils.isNotEmpty(params.get("rank"))) {
			entity.setRank(Integer.valueOf(params.get("rank")));
		}
		if (StringUtils.isNotEmpty(params.get("age"))) {
			entity.setRank(Integer.valueOf(params.get("age")));
		}
		if (StringUtils.isNotEmpty(params.get("sex"))) {
			entity.setRank(Integer.valueOf(params.get("sex")));
		}
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.updateDiMedicineGroup(entity);
		return ReturnUtil.success();
	}

	/**
	 * 删除一条药品分组
	 * 
	 * @param seq
	 * @return
	 */
	public ReturnData deleteMedicineGroup(int seq) {
		dao.deleteMedicineGroupBySeq(seq);
		return ReturnUtil.success();
	}

	/**
	 * 删除一条疾病药品分组
	 * 
	 * @param seq
	 * @return
	 */
	public ReturnData deleteDiMedicineGroup(int seq) {
		dao.deleteDiMedicineGroupBySeq(seq);
		return ReturnUtil.success();
	}

	/**
	 * 导出药品分组列表
	 * 
	 * @param resp
	 * @throws IOException
	 */
	public void exportMedicineGroup(HttpServletResponse resp)
			throws IOException {
		RespHeaderUtil.setXlsxResp(resp, "medicine_group");
		List<MedicineGroup> dataList = dao.selectMedicineGroupListToExport();
		if (dataList == null || dataList.size() == 0) {
			return;
		}
		Workbook workbook = new XSSFWorkbook(); // 创建文档
		Sheet sheet = workbook.createSheet(); // 创建Sheet
		// 写入文件
		int i = 0;
		for (MedicineGroup line : dataList) {
			Row row = sheet.createRow(i);
			Cell cell1 = row.createCell(0);
			cell1.setCellValue(line.getGroupName());
			Cell cell2 = row.createCell(1);
			cell2.setCellValue(line.getId());
			Cell cell3 = row.createCell(2);
			cell3.setCellValue(line.getRank());
			i++;
		}
		OutputStream os = resp.getOutputStream();
		workbook.write(os);
		os.close();
		workbook.close();
	}

	/**
	 * 导出疾病药品分组列表
	 * 
	 * @param resp
	 * @throws IOException
	 */
	public void exportDiMedicineGroup(HttpServletResponse resp)
			throws IOException {
		RespHeaderUtil.setXlsxResp(resp, "di_medicine_group");
		List<DiMedicineGroup> dataList = dao
				.selectDiMedicineGroupListToExport();
		if (dataList == null || dataList.size() == 0) {
			return;
		}
		Workbook workbook = new XSSFWorkbook(); // 创建文档
		Sheet sheet = workbook.createSheet(); // 创建Sheet
		// 写入文件
		int i = 0;
		for (DiMedicineGroup line : dataList) {
			Row row = sheet.createRow(i);
			Cell cell1 = row.createCell(0);
			cell1.setCellValue(line.getId());
			Cell cell2 = row.createCell(1);
			cell2.setCellValue(line.getDi());
			Cell cell3 = row.createCell(2);
			cell3.setCellValue(line.getRank());
			Cell cell4 = row.createCell(3);
			cell4.setCellValue(line.getAge());
			Cell cell5 = row.createCell(4);
			cell5.setCellValue(line.getSex());
			i++;
		}
		OutputStream os = resp.getOutputStream();
		workbook.write(os);
		os.close();
		workbook.close();
	}

	/**
	 * 插入一条药品分组
	 * 
	 * @param params
	 * @param user
	 */
	private void insertMedicineGroup(Map<String, String> params, User user) {
		MedicineGroup entity = new MedicineGroup();
		entity.setGroupName(params.get("groupName"));
		entity.setId(Integer.valueOf(params.get("id")));
		entity.setRank(Integer.valueOf(params.get("rank")));
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.insertMedicineGroup(entity);
	}

	/**
	 * 插入一条疾病药品分组
	 * 
	 * @param params
	 * @param user
	 */
	private void insertDiMedicineGroup(Map<String, String> params, User user) {
		DiMedicineGroup entity = new DiMedicineGroup();
		entity.setId(Integer.valueOf(params.get("id")));
		entity.setDi(params.get("di"));
		entity.setRank(Integer.valueOf(params.get("rank")));
		entity.setAge(Integer.valueOf(params.get("age")));
		entity.setSex(Integer.valueOf(params.get("sex")));
		entity.setModifierId(user.getUserId());
		entity.setModifierName(user.getRealName());
		dao.insertDiMedicineGroup(entity);
	}

}
